<template>
  <div>
    <Modal
      class="add_form"
      v-model="visible"
      :title="`${pluginId ? '编辑' : '创建'}插件`"
      :mask-closable="false"
      draggable
      sticky
      scrollable
      @on-cancel="cancel"
      width="80vw"
      :styles="{ top: '20px' }"
    >
      <div style="height: 70vh">
        <Form ref="formEl" :model="formData" :rules="rules" label-position="top">
          <FormItem label="插件名称" prop="name">
            <Input
              v-model="formData.name"
              placeholder="请输入插件名称"
              clearable
              maxlength="30"
              show-word-limit
            ></Input>
          </FormItem>
          <FormItem label="插件描述" prop="description">
            <Input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入插件描述"
              maxlength="100"
              show-word-limit
              clearable
            ></Input>
          </FormItem>
          <FormItem label="插件路径" prop="toolurl">
            <Input v-model="formData.toolurl" placeholder="请输入插件路径" clearable></Input>
          </FormItem>
          <FormItem label="请求方法" prop="reqmethod">
            <Select v-model="formData.reqmethod" placeholder="请输入请求方法" clearable>
              <Option v-for="item in bodyTypeGather" :value="item.code" :key="item.id">
                {{ item.name }}
              </Option>
            </Select>
          </FormItem>
          <!-- 输入 -->
          <div class="flex_form_item">
            <p>配置输入参数</p>
            <Button size="small" @click="handleAddInput('configinlist')" icon="md-add"
              >新增参数</Button
            >
          </div>
          <el-table :data="formData.configinlist" style="width: 100%">
            <el-table-column label="参数名称" prop="varname" min-width="200px">
              <template #header>
                <p>参数名称 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configinlist.' + $index + '.varname'"
                  :rules="{
                    required: true,
                    message: '请输入参数名称',
                    trigger: 'blur'
                  }"
                >
                  <Input v-model="row.varname" placeholder="请输入参数名称" size="small"></Input>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="参数描述" prop="vardesc" min-width="200px">
              <template #header>
                <p>参数描述 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configinlist.' + $index + '.vardesc'"
                  :rules="{
                    required: true,
                    message: '请输入参数描述',
                    trigger: 'blur'
                  }"
                >
                  <Input
                    v-model="row.vardesc"
                    size="small"
                    placeholder="参数描述"
                    show-word-limit
                    maxlength="50"
                  ></Input>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="参数类型" prop="vartype" min-width="120px">
              <template #header>
                <p>参数类型 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configinlist.' + $index + '.vartype'"
                  :rules="{
                    required: true,
                    message: '请选择参数类型',
                    trigger: 'change'
                  }"
                >
                  <Select v-model="row.vartype" transfer size="small">
                    <Option v-for="item in BE_TYPE_LIST" :value="item.value" :key="item.value">{{
                      item.value
                    }}</Option>
                  </Select>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="传入方法" prop="method" min-width="120px">
              <template #header>
                <p>传入方法 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configinlist.' + $index + '.method'"
                  :rules="{
                    required: true,
                    message: '请选择传入方法',
                    trigger: 'change'
                  }"
                >
                  <Select v-model="row.method" transfer size="small">
                    <Option v-for="item in bodyTypeGather" :value="item.code" :key="item.id">
                      {{ item.name }}
                    </Option>
                  </Select>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="是否必要" prop="isrequired" min-width="100px" align="center">
              <template #default="{ $index, row }">
                <FormItem :key="$index">
                  <Checkbox v-model="row.isrequired" size="small" />
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="默认值" prop="defaultval" min-width="120px">
              <template #default="{ $index, row }">
                <FormItem :key="$index">
                  <Input v-model="row.defaultval" size="small" />
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="开启" prop="isopen" min-width="100px">
              <template #default="{ $index, row }">
                <FormItem :key="$index">
                  <Switch v-model="row.isopen" size="small" />
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="70px">
              <template #default="scope">
                <Icon
                  class="cursor-pointer"
                  size="20"
                  type="ios-trash"
                  @click="handleInputRemove('configinlist', scope.$index)"
                ></Icon>
              </template>
            </el-table-column>
          </el-table>

          <!-- 输出 -->
          <div class="flex_form_item">
            <p>配置输出参数</p>
            <Button size="small" @click="handleAddInput('configoutlist')" icon="md-add"
              >新增参数</Button
            >
          </div>
          <el-table :data="formData.configoutlist" style="width: 100%">
            <el-table-column label="参数名称" prop="varname" min-width="200px">
              <template #header>
                <p>参数名称 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configoutlist.' + $index + '.varname'"
                  :rules="{
                    required: true,
                    message: '请输入参数名称',
                    trigger: 'blur'
                  }"
                >
                  <Input v-model="row.varname" placeholder="请输入参数名称" size="small"></Input>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="参数描述" prop="vardesc" min-width="200px">
              <template #header>
                <p>参数描述 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configoutlist.' + $index + '.vardesc'"
                  :rules="{
                    required: true,
                    message: '请输入参数描述',
                    trigger: 'blur'
                  }"
                >
                  <Input
                    v-model="row.vardesc"
                    size="small"
                    placeholder="参数描述"
                    show-word-limit
                    maxlength="50"
                  ></Input>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="参数类型" prop="vartype" min-width="120px">
              <template #header>
                <p>参数类型 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configoutlist.' + $index + '.vartype'"
                  :rules="{
                    required: true,
                    message: '请选择参数类型',
                    trigger: 'change'
                  }"
                >
                  <Select v-model="row.vartype" transfer size="small">
                    <Option v-for="item in BE_TYPE_LIST" :value="item.value" :key="item.value">{{
                      item.label
                    }}</Option>
                  </Select>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="传入方法" prop="method" min-width="120px">
              <template #header>
                <p>传入方法 <span style="color: red">*</span></p>
              </template>
              <template #default="{ $index, row }">
                <FormItem
                  :key="$index"
                  :prop="'configoutlist.' + $index + '.method'"
                  :rules="{
                    required: true,
                    message: '请选择传入方法',
                    trigger: 'change'
                  }"
                >
                  <Select v-model="row.method" transfer size="small">
                    <Option v-for="item in bodyTypeGather" :value="item.code" :key="item.id">
                      {{ item.name }}
                    </Option>
                  </Select>
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="是否必要" prop="isrequired" min-width="100px" align="center">
              <template #default="{ $index, row }">
                <FormItem :key="$index">
                  <Checkbox v-model="row.isrequired" size="small" />
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="默认值" prop="defaultval" min-width="120px">
              <template #default="{ $index, row }">
                <FormItem :key="$index">
                  <Input v-model="row.defaultval" size="small" />
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="开启" prop="isopen" min-width="100px">
              <template #default="{ $index, row }">
                <FormItem :key="$index">
                  <Switch v-model="row.isopen" size="small" />
                </FormItem>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="70px">
              <template #default="scope">
                <Icon
                  class="cursor-pointer"
                  size="20"
                  type="ios-trash"
                  @click="handleInputRemove('configoutlist', scope.$index)"
                ></Icon>
              </template>
            </el-table-column>
          </el-table>
        </Form>
      </div>

      <template #footer>
        <Button @click="cancel">取消</Button>
        <Button type="primary" :loading="loading" @click="submit">确定</Button>
      </template>
    </Modal>
  </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import { Message } from 'view-ui-plus'

import { createPlugin, updatePlugin, detailPlugin } from '@/api/modules/plugin'
import { dicCode } from '@/api/modules/flow'
import { BE_TYPE_LIST } from '@/components/FlowCanvas/lib/constant'

const props = defineProps({
  parentId: [String, Number]
})
const emit = defineEmits(['submit'])
const visible = ref(false)
const pluginId = ref(undefined)
// 加载
const loading = ref(false)
// 表单元素ref
const formEl = ref(null)

// 表单字段
const formData = ref({
  name: '',
  description: '',
  toolurl: '',
  reqmethod: '',
  configinlist: [],
  configoutlist: []
})

// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
  description: [{ required: true, message: '请填写描述', trigger: 'blur' }],
  toolurl: [{ required: true, message: '请填写路径', trigger: 'blur' }],
  reqmethod: [{ required: true, message: '请选择请求方法', trigger: 'blur' }]
})
const initDialog = async (id) => {
  pluginId.value = id
  if (id) {
    const { data } = await detailPlugin({ data: { id } })
    formData.value.name = data.name
    formData.value.description = data.description
    formData.value.toolurl = data.toolurl
    formData.value.reqmethod = data.reqmethod
    formData.value.configinlist = data.configinlist || []
    formData.value.configoutlist = data.configoutlist || []
  }
  visible.value = true
}

const bodyTypeGather = ref([])
const getBodyTypeData = () => {
  dicCode({
    data: {
      code: 'com.dic.aiflow.http.request'
    }
  }).then(({ data }) => {
    data.shift()
    bodyTypeGather.value = data
  })
}
getBodyTypeData()

const handleAddInput = (key) => {
  formData.value[key].push({
    varname: '',
    vartype: '',
    method: '',
    isrequired: true,
    isopen: true,
    defaultval: '',
    vardesc: ''
  })
}

const handleInputRemove = (key, index) => {
  formData.value[key].splice(index, 1)
}
/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate((valid, fild) => (valid ? valid : fild))
  if (!valid) return
  loading.value = true
  try {
    await (pluginId.value ? updatePlugin : createPlugin)({
      data: { 
        ...formData.value, 
        id: pluginId.value || undefined,
        parentid: props.parentId 
      }
    })
    Message.success('提交成功')
    cancel()
    emit('submit')
  } catch (error) {
    console.log(error)
  }

  loading.value = false
}

const cancel = () => {
  visible.value = false
  formEl.value.resetFields()
  formData.value.configinlist = []
  formData.value.configoutlist = []
}

defineExpose({
  initDialog
})
</script>
<style lang="scss" scoped>
.select-box {
  width: 100%;
  height: 400px;
  border: 1px solid #eee;
  border-radius: 8px;
  display: flex;
  overflow: hidden;
  .left {
    flex-basis: 50%;
    height: 100%;
    padding: 10px;
    border-right: 1px solid #eee;
    overflow: hidden;
  }
  .select-list {
    height: calc(100% - 30px);
    overflow-y: auto;
    overflow-x: hidden;
    padding-top: 10px;
    padding-right: 4px;
  }
  .select-item {
    width: 100%;
    margin: 5px 0;
    width: 100%;
    font-size: 15px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .flex-item {
    width: 100%;
    display: inline-flex;
    align-items: center;
    justify-content: space-between;
    margin: 6px 0;
    width: 100%;
    p {
      flex: 1;
      font-size: 15px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
  .right {
    flex-basis: 50%;
    padding: 10px;
    overflow: hidden;
    &-header {
      padding-top: 10px;
      font-size: 14px;
      color: #333;
    }
  }
}
</style>
